package com.haiyou.dc.message.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.haiyou.dc.message.constant.OpenfireConstant;
import lombok.extern.slf4j.Slf4j;
import org.jivesoftware.openfire.OfflineMessageStore;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.session.ClientSession;
import org.jivesoftware.openfire.session.Session;
import org.jivesoftware.openfire.user.UserManager;
import org.xmpp.packet.Message;

import java.util.Collection;

/**
 * @author pc
 */
@Slf4j
public class SendMsgUtil {
    /**
     * 发送消息到openfire下
     *
     * @param body json体
     */
    public static void sendMsg(String body) {
        JSONObject json = JSON.parseObject(body);
        String type = json.getString(OpenfireConstant.TYPE);
        if (OpenfireConstant.CREATE_USER.equals(type)) {
            createUser(json);
        } else if (OpenfireConstant.SINGLE_CHAT.equals(type)) {
            sendSingleMsg(json);
        } else if (OpenfireConstant.GROUP_CHAT.equals(type)) {
            sendGroupMsg(json);
        } else {
            log.info("其他系统消息===>" + body);
            sendSingleMsg(json);
        }
    }

    /**
     * 群消息发送，默认3人群
     *
     * @param json 消息体
     */
    private static void sendGroupMsg(JSONObject json) {
        String receivers = json.getString("receivers");
        String[] arr = receivers.split(",");
        if (arr.length > 0) {
            for (int i = 0; i < arr.length; i++) {
                String receiver = arr[i];
                if (receiver != null && receiver.trim().length() > 0) {
                    json.put("receiver", receiver);
                    sendSingleMsg(json);
                }
            }
        }
    }

    /**
     * 消息发送逻辑
     *
     * @param json 消息体
     */
    private static void sendSingleMsg(JSONObject json) {
        Message message = new Message();
        message.setBody(json.toJSONString());
        String receiver = json.getString("receiver");
        Collection<ClientSession> sessions = null;
        if (OpenfireConstant.SEND_RECEIVER.equals(receiver)) {
            //群发
            log.info("receiver=0,json===>" + json);
            sessions = SessionManager.getInstance().getSessions();
        } else {
            log.info("receiver====>" + receiver + ",json===>" + json);
            //根据用户名发送
            sessions = SessionManager.getInstance().getSessions(receiver);
        }
        /**
         * 根据用户名获取session列表
         */
        if (sessions != null && sessions.size() > 0) {
            sessions.forEach(session -> {
                sendMsg(message, session);
            });
        } else {
            log.info("对方已经离线，存储离线消息");
            message.setTo(receiver + "@" + XMPPServer.getInstance().getServerInfo().getXMPPDomain());
            message.setType(Message.Type.chat);
            OfflineMessageStore.getInstance().addMessage(message);
        }
    }


    /**
     * 发送消息
     *
     * @param message 消息
     * @param session 会话
     */
    private static void sendMsg(Message message, Session session) {
        log.info("send to===>" + session.getAddress());
        message.setFrom(session.getAddress());
        message.setTo(session.getAddress());
        //设置普通聊天类型
        message.setType(Message.Type.chat);
        session.process(message);
    }

    /**
     * 创建用户
     *
     * @param json 用户信息json
     */
    public static void createUser(JSONObject json) {
        try {
            String username = json.getString("username");
            if (StringUtil.isBlank(username)) {
                return;
            }
            if (!UserManager.getInstance().isRegisteredUser(username)) {
                log.info("用户正在注册===>username==>" + username);
                UserManager.getInstance().createUser(username, "123456", null, null);
            } else {
                log.info("用户已存在===>username==>" + username);
            }
        } catch (Exception e) {
            log.error("注册/创建用户失败===>" + e.getMessage(), e);
        }
    }
}
